job "api" {
  datacenters = ["dc1"]
  type        = "service"

  group "api" {
    count = 1  # API服务通常需要更多实例

    network {
      port "http" {
        static = 8888
      }
    }

    service {
      name = "api"
      tags = ["http", "api"]
      port = "http"
    }

    scaling {
      enabled = true
      min     = 1
      max     = 5

      policy {
        cooldown  = "5m"
        evaluation_interval = "30s"

        # 基于请求率的扩缩容
        metrics {
          type = "prometheus"
          source = "http://127.0.0.1:9090"
          query = <<EOT
              sum(rate(http_requests_total{job="api"}[1m]))
            EOT
        }

        target {
          nomad_autoscaler {
            policy = "target-value"
            target_value = 100  # 每秒200请求时扩容
          }
        }
      }
    }

    task "api-http" {
      driver = "docker"

      config {
        image = "registry.cn-hangzhou.aliyuncs.com/my_public_images/api:latest"
        ports = ["http"]
      }

      resources {
        cpu    = 500
        memory = 512  # API服务通常需要更多内存
      }

      env {
        NOMAD_HOST_IP     = "${NOMAD_HOST_IP_http}"
        PORT              = "${NOMAD_PORT_http}"
        USER_RPC_ADDR     = "127.0.0.1:8001"
        ORDER_RPC_ADDR    = "127.0.0.1:8002"
        JAEGER_AGENT_HOST = "jaeger-agent.service.consul"
        JAEGER_AGENT_PORT = "6831"
      }
    }
  }
}